﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;
using Nivdal.AuxCode;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;

namespace Nivdal
{
    /// <summary>
    /// Summary description for ChatWebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class ChatWebService : System.Web.Services.WebService
    {

        [WebMethod]
     public string HelloWorld(string par1)
        {
            //OnlineUser OU = (OnlineUser)Context.Session["User"];
            //OU.UserId
           
            //Session["Count"] = "15";
            //// get the Count out of Session State
            //int? Count = (int?)Session["Count"];
 
            //if (Count == null)
            //    Count = 0;
 
            //// increment and store the count
            //Count++;
            //Session["Count"] = Count;
            int Count = 15;
 
            return "Hello World - Call Number: " + Count.ToString();

        }

        [WebMethod]
        public string WS_OpenNewChatByUser(string FriendId)
        {
             //OnlineUser OU = (OnlineUser)Context.Session["User"];
             GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
             string UserId = GND.ReturnUserId();
             return (GND.ReadNivdalIntData("@UserId", "@FriendId", "Nivdal_OpenNewChatRoom", UserId, FriendId));

        }

        [WebMethod]
        public string WS_ReturnTranslatedString(string StringToTranslate)
        {
            string RerurnValue = "";
            switch (StringToTranslate)
            {
                case "Chat_NoRoomAvail":
                    RerurnValue = (Resources.Resource.Chat_NoRoomAvail);
                    break;
                case "Chat_FriendNotAvailForChat":
                    RerurnValue = (Resources.Resource.Chat_FriendNotAvailForChat);
                    break;
                case "Chat_TitleMessage":
                    RerurnValue = (Resources.Resource.Chat_TitleMessage);
                    break;
                default:
                    return StringToTranslate;
            }

            return RerurnValue;

        }

        [WebMethod]
        public string WS_LookForNewChats(string ChatroomId1, string ChatroomId2, string ChatroomId3, string ChatroomId4)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            
            try
            {
                string UserId = GND.ReturnUserId();
                return (GND.ReadNivdalStringData("@UserId", "@ChatroomId1", "@ChatroomId2", "@ChatroomId3", "@ChatroomId4", "Nivdal_LookForNewChats", UserId, ChatroomId1, ChatroomId2, ChatroomId3, ChatroomId4));

            }
            catch
            {
               // return "Error on WS_LookForNewChats";
                return "0,0,0";
            }

        }

        [WebMethod]
        public bool WS_ReadUserTypingInfo(string ChatroomId)
        //Calls Nivdal_ReadUserTypingInfo stored procedure to check whether the opponent is typing or not
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            string UserId = GND.ReturnUserId();
            return (GND.ReadNivdalBoolData("@UserId", "@ChatroomId", "Nivdal_ReadUserTypingInfo", UserId, ChatroomId));
        }

        [WebMethod]
        public string WS_ReadNewMessages(string RoomId, string LastMessageId)
        {
            if (RoomId == "0")
                return "";
            else
            {
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                string UserId = GND.ReturnUserId();
                string NewMessage = "";
                decimal MessageId = 0;
                Boolean ShouldPlaySound = false;
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                SqlCommand cmd = new SqlCommand("Nivdal_ChatReadNewMessages", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataReader reader;
                
                cmd.Parameters.AddWithValue("UserId", UserId);
                cmd.Parameters.Add("ChatroomId", SqlDbType.Decimal, 12);
                cmd.Parameters["ChatroomId"].Value = RoomId;
                cmd.Parameters.Add("LastMessageId", SqlDbType.Decimal, 12);
                cmd.Parameters["LastMessageId"].Value = LastMessageId;
                //cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@UserId", UserId));
                //cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ChatroomId", RoomId));
                //cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@LastMessageId", LastMessageId));
                try
                {
                    conn.Open();
                    reader = cmd.ExecuteReader();
                    if (reader.HasRows)
                        while (reader.Read())
                        {
                            MessageId = reader.GetDecimal(0);
                            NewMessage = GlobalFunctions.LightEncodeHtmlFromText(NewMessage + "<br /> " + reader.GetString(1));
                            ShouldPlaySound = reader.GetBoolean(2);
                            ///NewMessage = NewMessage + "<span style=\"color:#658321;font-weight:bold;\">" + reader.GetString(0) + ":</span> ";
                        }

                }
                catch (Exception SQLDBException)
                {

                    return (Convert.ToString(SQLDBException)); //remove after debugging 

                }

                finally
                {
                    // Close the connection when done with it.
                    conn.Close();

                }

                if (NewMessage.Length > 0)
                    return MessageId.ToString() + "<>" + NewMessage + "<>" + ShouldPlaySound.ToString();
                else
                    return "";

            }
        }

        [WebMethod]
        public  void WS_CloseChatByUser(string ChatroomId)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            string UserId = GND.ReturnUserId();
            GND.ExecNivdalSQL("@UserId", "@ChatroomId", "Nivdal_UserExitsFromChatRoom", UserId, ChatroomId);   

        }

        [WebMethod]
        public void WS_UpdateUserTyping(string ChatroomId)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            string UserId = GND.ReturnUserId();
            GND.ExecNivdalSQL("@UserId", "@ChatroomId", "Nivdal_UpdateUserTyping", UserId, ChatroomId);
            //GND.ExecNivdalSQL("@UserId", "@ChatroomId", "Nivdal_UpdateUserTyping", 3323434, 33);
             
        }

        [WebMethod]
        public void WS_AddChatMessage(string ChatRoomId, string Text)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            string UserId = GND.ReturnUserId();
            Text = Text.Replace('<', '(').Replace('>',')').Trim();
            if (Text.Length > 0)
              GND.ReadNivdalStringData("@UserId", "@ChatRoomId", "@Text", "Nivdal_AddChatMessage", UserId, ChatRoomId, Text);  
        }

        [WebMethod]
        public string WS_IsUserOnline(string ChatRoomId)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            string UserId = GND.ReturnUserId();
            bool ReturnValue = false;
            try
            {
                ReturnValue = GND.ReadNivdalBoolData("@UserId", "@ChatroomId", "Nivdal_IsChatFriendOnline", UserId, ChatRoomId);

            }
            catch
            {
                ReturnValue = false;
            }

            return ReturnValue ? "true" : "false";
        }


    }
}
